package com.ttg.web.service.Impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ttg.common.entities.BaseResult;
import com.ttg.common.enums.CouponTagAndGradeStatusEnum;
import com.ttg.common.enums.ErrorCodeEnums;
import com.ttg.common.enums.SendToCouponGetTagStatusEnum;
import com.ttg.common.exception.BaseException;
import com.ttg.common.utils.*;
import com.ttg.model.dto.coupon.SendToCouponGetTagStatusDto;
import com.ttg.model.dto.coupon.TagUsedListDTO;
import com.ttg.model.dto.open.TagStatisticsDto;
import com.ttg.model.dto.open.TagStatisticsListDto;
import com.ttg.model.dto.open.VipTagDto;
import com.ttg.model.dto.open.VipTagListDto;
import com.ttg.model.pojo.TagHis;
import com.ttg.model.pojo.TagInfo;
import com.ttg.model.pojo.VipBindTag;
import com.ttg.model.vo.coupon.GradeTagListUsedVO;
import com.ttg.model.pojo.VipInfo;
import com.ttg.model.vo.coupon.SendToCouponGetTagStatusVo;
import com.ttg.model.vo.open.TagSyncVo;
import com.ttg.web.dao.AdminDao;
import com.ttg.web.dao.TagHisDao;
import com.ttg.model.vo.open.VipInfoVo;
import com.ttg.web.dao.VipBindTagDao;
import com.ttg.web.dao.VipInfoDao;
import com.ttg.web.manage.HttpRequestExample;
import com.ttg.web.service.GradeToCouponService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class GradeToCouponServiceImpl implements GradeToCouponService {

    @Value("${coupon.aes.key}")
    private String aesKey;

    @Value("${coupon.rsa.privateKey}")
    private String rsaPrivateKey;

    @Value("${coupon.rsa.publicKey}")
    private String rsaPublicKey;

    @Value("${coupon.path}")
    private String path;

    @Value("${coupon.pathTzg}")
    private String pathTzg;

    @Value("${coupon.eopId}")
    private String eopId;

    @Value("${coupon.getTagStatusUrl}")
    private String getTagStatusUrl;

    @Value("${coupon.taggradeTagList}")
    private String taggradeTagList;

    @Value("${coupon.org1GxdUpDateTags}")
    private String org1GxdUpDateTags;

    @Value("${coupon.tzgKey}")
    private String tzgKey;

    @Autowired
    private HttpRequestExample httpRequestExample;

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private TagHisDao tagHisDao;

    @Value("${coupon.getTagUsedAllUrl:/taggrade/usedAll}")
    private String getTagUsedAllUrl;

    @Value("${coupon.tagStatisticsList:/taggrade/tagStatisticsList}")
    private String tagStatisticsListUrl;

    @Value("${coupon.vipTagList:/taggrade/vipTagList}")
    private String vipTagListUrl;

    @Autowired
    private VipInfoDao vipInfoDao;
    @Autowired
    private VipBindTagDao vipBindTagDao;

    @Override
    public boolean sendToCouponGetTagStatus(Long tagId) {
        SendToCouponGetTagStatusDto dto = new SendToCouponGetTagStatusDto();
        dto.setId(tagId);
        dto.setType(SendToCouponGetTagStatusEnum.TAG.getValue());
        String res = "";
        try {
            res = sendToCoupon(getTagStatusUrl, JsonUtils.objectToJson(dto));
        } catch (Exception e) {
            log.error("【GradeToCouponServiceImpl sendToCouponGetTagStatus】", e);
            return false;
        }
        SendToCouponGetTagStatusVo sendToCouponGetTagStatusVo = JsonUtils.jsonToObject(res, SendToCouponGetTagStatusVo.class);
        if (CouponTagAndGradeStatusEnum.TAG_GRADE_TYPE_DEFAULT.getCode().equals(sendToCouponGetTagStatusVo.getStatus())) {
            return true;
        }
        return false;
    }

    @Override
    public boolean sendToCouponTaggradeTagList(List<TagInfo> tagInfos) {
        List<TagSyncVo> voList = new ArrayList<>();
        for (TagInfo tagInfo : tagInfos) {
            if (ObjectUtil.isNotNull(tagInfo)) {
                TagSyncVo v = tagHisDao.getSycnTag(tagInfo.getId());
                voList.add(v);
            }
        }
        boolean f = true;
        try {
            HashMap<String, Object> map = new HashMap<>();
            map.put("tagList", voList);
            log.info("syncTag send url: {}, param: {}", taggradeTagList, JsonUtils.objectToJson(map));
            String result=sendToCoupon(taggradeTagList, JsonUtils.objectToJson(map));
            log.info("syncTag return: {}", result);
        } catch (Exception e) {
            log.error("【GradeToCouponServiceImpl sendToCouponTaggradeTagList】", e);
            f = false;
        }

        try {
            HashMap<String, Object> map = new HashMap<>();
            map.put("tagList", voList);
            map.put("tagListKey", tzgKey);
            sendToCouponTzg(org1GxdUpDateTags, map);
        } catch (Exception e) {
            log.error("【GradeToCouponServiceImpl sendToCouponTaggradeTagList】", e);
            f = false;
        }


        return f;
    }

    @Override
    public boolean sendToVipList(List<VipInfo> vipInfos) {
        List<VipInfoVo> voList = new ArrayList<>();
        for (VipInfo vipInfo : vipInfos) {
            if (ObjectUtil.isNotNull(vipInfo)) {
                VipInfoVo vipInfoVo = vipInfoDao.getSycnVip(vipInfo.getVipId());
                voList.add(vipInfoVo);
            }
        }
        boolean f = true;
        try {
            HashMap<String, Object> map = new HashMap<>();
            map.put("tagList", voList);
            sendToCoupon(taggradeTagList, JsonUtils.objectToJson(map));
        } catch (Exception e) {
            log.error("【GradeToCouponServiceImpl sendToCouponTaggradeTagList】", e);
            f = false;
        }

        try {
            HashMap<String, Object> map = new HashMap<>();
            map.put("tagList", voList);
            map.put("tagListKey", tzgKey);
            sendToCouponTzg(org1GxdUpDateTags, map);
        } catch (Exception e) {
            log.error("【GradeToCouponServiceImpl sendToCouponTaggradeTagList】", e);
            f = false;
        }


        return f;
    }


    String sendToCoupon(String url, String data) throws Exception {
        TreeMap<String, String> postMap = new TreeMap<>();
        log.info("【GradeToCouponServiceImpl sendToCoupon】data发送数据===>{}", data);
        postMap.put("timestamp", System.currentTimeMillis() / 1000 + "");
        postMap.put("randStr", RandomStringUtils.randomAlphabetic(32));
        postMap.put("eopId", eopId);
        String s = AesUtil.encrypt(data, aesKey.getBytes(StandardCharsets.UTF_8));
        postMap.put("data", s);
        String sort = BasicUtils.sort(postMap);
        String s1 = BasicUtils.SHAL1(sort);

        String sign = RsaUtils.rsaSignByPrivateKey(s1, rsaPrivateKey);

        postMap.put("sign", sign);
        String address = path + url;
        log.info("【GradeToCouponServiceImpl sendToCoupon】请求数据===>{},请求地址====>{}", postMap, address);
        String res = httpRequestExample.sendPostRequestToCoupon(address, JsonUtils.objectToJson(postMap), eopId);
        log.info("【GradeToCouponServiceImpl sendToCoupon】请求数据返回===>{}", res);

        BaseResult baseResult = JsonUtils.jsonToObject(res, BaseResult.class);
        Object data1 = baseResult.getData();
        log.info("【GradeToCouponServiceImpl sendToCoupon】data接收数据===>{}", data1);

        if (Objects.nonNull(data1) && StringUtils.isNotEmpty(res)) {
            String sign2 = baseResult.getSign();
            TreeMap<String, String> treeMap = new TreeMap<>();
            treeMap.put("errcode", "0");
            treeMap.put("msg", baseResult.getMsg());
            String data11 = (String) data1;
            treeMap.put("data", data11);
            String sort2 = BasicUtils.sort(treeMap);
            String shal1 = BasicUtils.SHAL1(sort2);
            if (RsaUtils.verify(shal1.getBytes(StandardCharsets.UTF_8), rsaPublicKey, sign2)) {
                String decrypt = SecurityUtils.decrypt(data11, aesKey);
                log.info("【GradeToCouponServiceImpl sendToCoupon】解密data数据===>{}", decrypt);
                return decrypt;
            }

        }

        log.error("【GradeToCouponServiceImpl sendToCoupon】请求数据返回异常====>{}", res);
        throw new BaseException(ErrorCodeEnums.REQUEST_COUPON_DATA_GET_ERROR);


    }

    String sendToCouponTzg(String url, Map<String, Object> map) throws Exception {
        final String[] split = pathTzg.split(",");
        for (String tzg : split) {
            try {
                String address = tzg + url;
                log.info("【GradeToCouponServiceImpl sendToCoupon】请求数据===>{},请求地址====>{}", JsonUtils.objectToJson(map), address);
                String res = httpRequestExample.sendPostRequest(address, JsonUtils.objectToJson(map), eopId);
                log.info("【GradeToCouponServiceImpl sendToCoupon】请求数据返回===>{}", res);

                BaseResult baseResult = JsonUtils.jsonToObject(res, BaseResult.class);
                Object data1 = baseResult.getData();
                log.info("【GradeToCouponServiceImpl sendToCoupon】data数据===>{}", data1);

                if (Objects.nonNull(data1) && StringUtils.isNotEmpty(res)) {
                    return data1.toString();

                }

                log.error("【GradeToCouponServiceImpl sendToCoupon】请求数据返回异常====>{}", res);
                throw new BaseException("请求佟掌柜数据异常,路径:" + tzg + url);
            } catch (BaseException e) {
                log.error("佟掌柜请求数据异常:", e);
            }
        }
        throw new BaseException("请求佟掌柜数据异常");
    }


    @Override
    public GradeTagListUsedVO getTagUsed(TagUsedListDTO dto) {
        dto.setType(SendToCouponGetTagStatusEnum.TAG.getValue() + "");
        String res = "";
        try {
            log.info("getTagUsed url : " + getTagUsedAllUrl + "param: " + JsonUtils.objectToJson(dto));
            res = sendToCoupon(getTagUsedAllUrl, JsonUtils.objectToJson(dto));
            log.info("getTagUsed return : " + res);
        } catch (Exception e) {
            log.error("getTagUsed error", e);
        }
        GradeTagListUsedVO result = JsonUtils.jsonToObject(res, GradeTagListUsedVO.class);
        return result;
    }


    @Override
    public void syncTagStatistics(TagHis s) {
        try {
            TagStatisticsListDto dt=new TagStatisticsListDto();
            List<TagStatisticsDto> list = new ArrayList<>();
            TagStatisticsDto send = new TagStatisticsDto();
            send.setTagId(s.getTagId());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            send.setStatDate(sdf.format(s.getEndTime()));
            send.setTagUserCount(s.getTagPeopleNumber());
            list.add(send);
            dt.setTagStatisticsList(list);
            String res = "";
            log.info("syncTagStatistics url : " + tagStatisticsListUrl + "param: " + JsonUtils.objectToJson(dt));
            res = sendToCoupon(tagStatisticsListUrl, JsonUtils.objectToJson(dt));
            log.info("syncTagStatistics return : " + res);
        } catch (Exception e) {
            log.error("syncTagStatistics error", e);
        }
    }

    @Override
    public void syncTagMember(TagHis s, Set<Long> deleteVipMap) {
        try {
            VipTagListDto dto = new VipTagListDto();
            dto.setVipTagList(new ArrayList<>());

            // 使用LambdaQueryWrapper查询vipId列表
            LambdaQueryWrapper<VipBindTag> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(VipBindTag::getVipId);
            queryWrapper.eq(VipBindTag::getTagId, s.getTagId());

            // 直接获取vipId列表，处理Integer类型
            List<Object> vipIdObjects = vipBindTagDao.listObjs(queryWrapper);
            List<Integer> currentVipIds = vipIdObjects.stream()
                    .map(obj -> (Integer) obj)
                    .collect(Collectors.toList());

            // 处理当前标签下的会员（状态0）
            for (Integer vipId : currentVipIds) {
                VipTagDto tagDto = new VipTagDto();
                tagDto.setVtTagId(s.getTagId());
                tagDto.setVtVipId(vipId); // 直接使用Integer，不需要转换
                tagDto.setVtStatus(0);
                tagDto.setVtSyncTime(s.getEndTime());
                dto.getVipTagList().add(tagDto);
            }

            // 处理需要删除的会员（状态1）
            if (deleteVipMap != null && !deleteVipMap.isEmpty() && !deleteVipMap.contains(null)) {
                // 将deleteVipMap中的Long转换为Integer进行比较
                Set<Integer> currentVipIdSet = currentVipIds.stream()
                        .collect(Collectors.toSet());
                Set<Integer> deleteVipIds = deleteVipMap.stream()
                        .map(Long::intValue) // 将Long转换为Integer
                        .collect(Collectors.toSet());

                for (Integer vipId : deleteVipIds) {
                    if (!currentVipIdSet.contains(vipId) || CollectionUtils.isEmpty(currentVipIdSet)) {
                        VipTagDto tagDto = new VipTagDto();
                        tagDto.setVtTagId(s.getTagId());
                        tagDto.setVtVipId(vipId);
                        tagDto.setVtStatus(1);
                        tagDto.setVtSyncTime(s.getEndTime());
                        dto.getVipTagList().add(tagDto);
                    }
                }
            }
            // 发送请求
            if(!CollectionUtils.isEmpty(dto.getVipTagList())){
                String requestJson = JsonUtils.objectToJson(dto);
                log.info("syncTagMember url: {}, param: {}", vipTagListUrl, requestJson);

                String response = sendToCoupon(vipTagListUrl, requestJson);
                log.info("syncTagMember return: {}", response);
            }

        } catch (Exception e) {
            log.error("syncTagMember error, tagId: {}", s != null ? s.getTagId() : "unknown", e);
        }
    }
}
